<template>
  <div id="channelList" style="width: 100%">
    <div class="page-header">
      <div class="page-title">
        <el-button icon="el-icon-back" link size="small" style="font-size: 20px; color: #000;"
                   @click="showDevice()"></el-button>
        <el-divider direction="vertical"></el-divider>
        通道列表
      </div>
      <div class="page-header-btn">
        <div v-if="!showTree" style="display: inline;">
          搜索:
          <el-input
            v-model="searchSrt"
            clearable
            placeholder="关键字"
            prefix-icon="el-icon-search"
            size="small"
            style="margin-right: 1rem; width: auto;"
            @input="search()"
          ></el-input>

          通道类型:
          <el-select
            v-model="channelType"
            default-first-option
            placeholder="请选择"
            size="small"
            style="width: 8rem; margin-right: 1rem;"
            @change="search()"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="设备" value="false"></el-option>
            <el-option label="子目录" value="true"></el-option>
          </el-select>
          在线状态:
          <el-select
            v-model="online"
            default-first-option
            placeholder="请选择"
            size="small"
            style="width: 8rem; margin-right: 1rem;"
            @change="search()"
          >
            <el-option label="全部" value=""></el-option>
            <el-option label="在线" value="true"></el-option>
            <el-option label="离线" value="false"></el-option>
          </el-select>
          码流类型重置:
          <el-select
            v-model="subStream"
            default-first-option
            placeholder="请选择码流类型"
            size="small"
            style="width: 16rem; margin-right: 1rem;"
            @change="subStreamChange()"
          >
            <el-option label="stream:0(主码流)" value="stream:0"></el-option>
            <el-option label="stream:1(子码流)" value="stream:1"></el-option>
            <el-option label="streamnumber:0(主码流-2022)" value="streamnumber:0"></el-option>
            <el-option label="streamnumber:1(子码流-2022)" value="streamnumber:1"></el-option>
            <el-option label="streamprofile:0(主码流-大华)" value="streamprofile:0"></el-option>
            <el-option label="streamprofile:1(子码流-大华)" value="streamprofile:1"></el-option>
            <el-option label="streamMode:main(主码流-水星+TP-LINK)" value="streamMode:main"></el-option>
            <el-option label="streamMode:sub(子码流-水星+TP-LINK)" value="streamMode:sub"></el-option>
          </el-select>
        </div>
        <el-button circle icon="Refresh" size="small" @click="refresh()"></el-button>
      </div>
    </div>
    <devicePlayer ref="devicePlayer"></devicePlayer>
    <el-container v-loading="isLoging" style="height: 82vh;">
      <el-main style="padding: 5px;">
        <el-table ref="channelListTable" :data="deviceChannelList" :height="winHeight"
                  header-row-class-name="table-header"
                  style="width: 100%">
          <el-table-column label="通道编号" min-width="180" prop="channelId"></el-table-column>
          <el-table-column label="设备编号" min-width="180" prop="deviceId"></el-table-column>
          <el-table-column label="通道名称" min-width="180" prop="name">
            <template v-slot:default="scope">
              <el-input v-show="scope.row.edit" v-model="scope.row.name" :maxlength="255"
                        clearable
                        placeholder="通道名称" show-word-limit />
              <span v-show="!scope.row.edit">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="快照" min-width="100">-->
<!--            <template v-slot:default="scope">-->
<!--              <el-image-->
<!--                :fit="'contain'"-->
<!--                :preview-src-list="getBigSnap(scope.row)"-->
<!--                :src="getSnap(scope.row)"-->
<!--                style="width: 60px"-->
<!--                @error="getSnapErrorEvent(scope.row.deviceId, scope.row.channelId)"-->
<!--              >-->
<!--                <div slot="error" class="image-slot">-->
<!--                  <i class="el-icon-picture-outline"></i>-->
<!--                </div>-->
<!--              </el-image>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="子节点数" min-width="100" prop="subCount"></el-table-column>
          <el-table-column label="厂家" min-width="100" prop="manufacture"></el-table-column>
          <el-table-column label="位置信息" min-width="120">
            <template v-slot:default="scope">
              <el-input
                v-show="scope.row.edit"
                v-model="scope.row.location"
                :maxlength="30"
                clearable
                placeholder="例:117.234,36.378"
                show-word-limit
              />
              <span v-show="!scope.row.edit">{{ scope.row.location }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小区名称" min-width="120">
            <template v-slot:default="scope">
              <el-select
                v-show="scope.row.edit" v-model="scope.row.communityId" filterable placeholder="请选择小区"
                style="width: 240px" @visible-change="maChange(scope.row)">
                <el-option v-for="item in communityList" :key="item.communityId" :label="item.name"
                           :value="item.communityId" />
              </el-select>
              <span v-show="!scope.row.edit">{{ scope.row.communityName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="区域名称" min-width="150">
            <template v-slot:default="scope">
              <el-select v-show="scope.row.edit" v-model="scope.row.maId" filterable placeholder="请选择区域"
                         style="width: 240px">
                <el-option v-for="item in maList" :key="item.maId" :label="item.maName" :value="item.maId" />
              </el-select>
              <span v-show="!scope.row.edit">{{ scope.row.maName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="云台类型" min-width="100" prop="ptzType">
            <template v-slot:default="scope">
              <el-select v-show="scope.row.edit" v-model="scope.row.ptzType" filterable
                         placeholder="云台类型">
                <el-option v-for="(value, key) in ptzTypes" :key="key" :label="value" :value="key" />
              </el-select>
              <div v-show="!scope.row.edit">{{ scope.row.ptzTypeText }}</div>
            </template>
          </el-table-column>
          <el-table-column label="开启音频" min-width="100">
            <template v-slot="scope">
              <el-switch v-model="scope.row.hasAudio" active-color="#409EFF"
                         @change="updateChannel(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="码流类型" min-width="180">
            <template v-slot="scope">
              <el-select
                v-model="scope.row.streamIdentification"
                default-first-option
                placeholder="请选择码流类型"
                size="small"
                style="margin-right: 1rem;"
                @change="channelSubStreamChange(scope.row)"
              >
                <el-option label="stream:0(主码流)" value="stream:0"></el-option>
                <el-option label="stream:1(子码流)" value="stream:1"></el-option>
                <el-option label="streamnumber:0(主码流-2022)" value="streamnumber:0"></el-option>
                <el-option label="streamnumber:1(子码流-2022)" value="streamnumber:1"></el-option>
                <el-option label="streamprofile:0(主码流-大华)" value="streamprofile:0"></el-option>
                <el-option label="streamprofile:1(子码流-大华)" value="streamprofile:1"></el-option>
                <el-option label="streamMode:main(主码流-水星+TP-LINK)" value="streamMode:main"></el-option>
                <el-option label="streamMode:sub(子码流-水星+TP-LINK)" value="streamMode:sub"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="100">
            <template v-slot="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag v-if="scope.row.status === true" size="small">在线</el-tag>
                <el-tag v-if="scope.row.status === false" size="small" type="info">离线</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="340">
            <template v-slot="scope">
              <el-button
                icon="el-icon-video-play"
                link
                size="small"
                v-bind:disabled="device == null || device.online === 0"
                @click="sendDevicePush(scope.row)"
              >播放
              </el-button>
              <el-button
                v-if="!!scope.row.streamId"
                icon="el-icon-switch-button"
                link
                size="small"
                style="color: #f56c6c"
                v-bind:disabled="device == null || device.online === 0"
                @click="stopDevicePush(scope.row)"
              >停止
              </el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button v-if="scope.row.edit" icon="el-icon-edit-outline" link size="small"
                         @click="handleSave(scope.row)"> 保存
              </el-button>
              <el-button v-else icon="el-icon-edit" link size="small" @click="handleEdit(scope.row)"> 编辑
              </el-button>
              <el-divider direction="vertical"></el-divider>
              <el-button
                v-if="scope.row.subCount > 0 || scope.row.parental === 1"
                icon="el-icon-s-open"
                link
                size="small"
                @click="changeSubchannel(scope.row)"
              >查看
              </el-button>
              <el-divider v-if="scope.row.subCount > 0 || scope.row.parental === 1"
                          direction="vertical"></el-divider>
              <el-button icon="el-icon-video-camera" link
                         size="small" @click="queryRecords(scope.row,device.onLine)">设备录像
              </el-button>
              <el-button icon="el-icon-cloudy" link
                         size="small" @click="queryCloudRecords(scope.row)">云端录像
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="currentPage"
          :page-size="count"
          :page-sizes="[15, 25, 35, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          style="float: right"
          @size-change="handleSizeChange"
          @current-change="currentChange"
        >
        </el-pagination>
      </el-main>
    </el-container>

    <!--设备列表-->
  </div>
</template>

<script>
import devicePlayer from "../dialog/devicePlayer.vue";
import { getDevice } from "@/api/video_monitor/DeviceService";
import {
  getChannelList,
  getSubChannelList,
  getTreeChannel,
  startPlay,
  stopPlay,
  updateChannel,
  updateStreamIdentification
} from "@/api/video_monitor/channel";
import { listCommunity } from "@/api/system/community";
import { listMonitorArea } from "@/api/wvp/monitorArea";
import { ElMessage } from "element-plus";

export default {
  name: "channelList",
  components: {
    devicePlayer
    // DeviceTree
  },
  data() {
    return {
      device: null,
      deviceId: this.$route.params.deviceId,
      parentChannelId: this.$route.params.parentChannelId,
      deviceChannelList: [],
      videoComponentList: [],
      currentPlayerInfo: {}, //当前播放对象
      updateLooper: 0, //数据刷新轮训标志
      searchSrt: "",
      channelType: "",
      online: "",
      subStream: "",
      winHeight: window.innerHeight - 200,
      currentPage: 1,
      count: 15,
      total: 0,
      beforeUrl: "/deviceList",
      isLoging: false,
      showTree: false,
      loadSnap: {},
      ptzTypes: {
        0: "未知",
        1: "球机",
        2: "半球",
        3: "固定枪机",
        4: "遥控枪机"
      },
      communityList: [],
      maList: []
    };
  },

  mounted() {
    if (this.deviceId) {
      getDevice(this.deviceId).then((result) => {
        this.device = result.data;
      }).catch((error) => {
        console.log("获取设备信息失败");
        console.error(error);
      });
    }
    this.initData();
  },
  unmounted() {
    // this.$destroy('videojs');;
    clearTimeout(this.updateLooper);
  },
  methods: {
    initData: function() {
      if (typeof (this.parentChannelId) == "undefined" || this.parentChannelId == 0) {
        this.getDeviceChannelList();
      } else {
        this.showSubchannels();
      }
    },
    initParam: function() {
      this.deviceId = this.$route.params.deviceId;
      this.parentChannelId = this.$route.params.parentChannelId;
      this.currentPage = 1;
      this.count = 15;
      if (this.parentChannelId == "" || this.parentChannelId == 0) {
        this.beforeUrl = "/deviceList";
      }

    },
    currentChange: function(val) {
      this.currentPage = val;
      this.initData();
    },
    handleSizeChange: function(val) {
      this.count = val;
      this.getDeviceChannelList();
    },
    getDeviceChannelList: async function() {
      if (typeof (this.$route.params.deviceId) == "undefined") return;
      let res = await getChannelList(this.$route.params.deviceId, this.currentPage, this.count, this.searchSrt,
        this.online, this.channelType);
      this.total = res.total;
      this.deviceChannelList = res.rows;
      console.log(this.deviceChannelList, "deviceChannelList");
      this.deviceChannelList.forEach(e => {
        e.ptzType = String(e.ptzType); // 将ptzType转换为字符串
        e.edit = false; // 直接设置属性，不需要 $set
        e.location = "";
        if (e.longitude && e.latitude) {
          e.location = `${e.longitude},${e.latitude}`; // 使用模板字符串连接经纬度
        }
      });
      // 防止出现表格错位
      this.$nextTick(() => {
        this.$refs.channelListTable.doLayout();
      });
    },

    //通知设备上传媒体流
    sendDevicePush: function(itemData) {
      let deviceId = this.deviceId;
      this.isLoging = true;
      let channelId = itemData.channelId;
      console.log("通知设备推流1：" + deviceId + " : " + channelId);
      let that = this;
      startPlay(deviceId, channelId).then(function(res) {
        console.log("res", res);
        that.isLoging = false;
        // setTimeout(() => {
        //   let snapId = deviceId + "_" + channelId;
        //   that.loadSnap[deviceId + channelId] = 0;
        //   that.getSnapErrorEvent(snapId);
        // }, 5000);
        itemData.streamId = res.data.stream;
        that.$refs.devicePlayer.openDialog("media", deviceId, channelId, {
          streamInfo: res.data,
          hasAudio: itemData.hasAudio
        });
        setTimeout(() => {
          that.initData();
        }, 1000);
      }).catch(function(e) {
        console.error(e);
        that.isLoging = false;
      });
    },
    moreClick: function(command, itemData) {
      if (command === "records") {
        this.queryRecords(itemData);
      } else if (command === "cloudRecords") {
        this.queryCloudRecords(itemData);
      }
    },
    queryRecords: function(itemData, de) {
      let deviceId = this.deviceId;
      let channelId = itemData.channelId;
      console.log(this.$router.path);
      this.$router.push(`/iot/video_monitor/gbRecordDetail/${deviceId}/${channelId}`);
    },
    queryCloudRecords: function(itemData) {
      let deviceId = this.deviceId;
      let channelId = itemData.channelId;
      console.log(this.$router.options.routes);
      this.$router.push(`/iot/video_monitor/cloudRecordDetail/rtp/${deviceId}_${channelId}`);
    },
    stopDevicePush: function(itemData) {
      var that = this;
      stopPlay(this.deviceId, itemData.channelId, this.isSubStream).then(function(res) {
        that.initData();
      }).catch(function(error) {
        if (error.response.status === 402) { // 已经停止过
          that.initData();
        } else {
          console.log(error);
        }
      });
    },
    getSnap: function(row) {
      const baseUrl = window.baseUrl ? window.baseUrl : "";
      const apiUrl = (import.meta.env.MODE === "development") ? import.meta.env.VITE_APP_BASE_API : baseUrl;
      console.log(`${apiUrl}/api/device/query/snap/${row.deviceId}/${row.channelId}`);
      return `${apiUrl}/api/device/query/snap/${row.deviceId}/${row.channelId}`;
    },
    getBigSnap: function(row) {
      return [this.getSnap(row)];
    },
    getSnapErrorEvent: function(deviceId, channelId) {

      if (typeof (this.loadSnap[deviceId + channelId]) != "undefined") {
        console.log("下载截图" + this.loadSnap[deviceId + channelId]);
        if (this.loadSnap[deviceId + channelId] > 5) {
          delete this.loadSnap[deviceId + channelId];
          return;
        }
        setTimeout(() => {
          const baseUrl = (import.meta.env.MODE === "development" ? "debug" : "");
          const url = `${baseUrl}/api/device/query/snap/${deviceId}/${channelId}`;
          this.loadSnap[deviceId + channelId]++;
          document.getElementById(deviceId + channelId).setAttribute("src", `${url}?${Date.now()}`);
        }, 1000);
      }
    },
    showDevice: function() {
      this.$router.push(this.beforeUrl).then(() => {
        this.initParam();
        this.initData();
      });
    },
    changeSubchannel(itemData) {
      this.beforeUrl = this.$router.currentRoute.value.path;
      var url = `/${this.$router.currentRoute.value.name}/${this.$router.currentRoute.value.params.deviceId}/${itemData.channelId}`;
      console.log("url", url);
      this.$router.push(url).then(() => {
        this.searchSrt = "";
        this.channelType = "";
        this.online = "";
        this.initParam();
        this.initData();
      });
    },
    showSubchannels: function(channelId) {
      if (!this.showTree) {
        getSubChannelList(this.deviceId, this.parentChannelId, this.currentPage,
          this.count, this.searchSrt, this.online, this.channelType).then((res) => {
          this.total = res.data.total;
          this.deviceChannelList = res.data.list;
          this.deviceChannelList.forEach(e => {
            e.ptzType = String(e.ptzType); // 将ptzType转换为字符串
            e.edit = false; // 直接设置属性，不需要 $set
            e.location = "";
            if (e.longitude && e.latitude) {
              e.location = `${e.longitude},${e.latitude}`; // 使用模板字符串连接经纬度
            }
          });
          // 防止出现表格错位
          this.$nextTick(() => {
            this.$refs.channelListTable.doLayout();
          });
        });
      } else {
        getTreeChannel(this.deviceId, this.parentChannelId, this.currentPage, this.count).then((res) => {
          if (res.data.code === 0) {
            this.total = res.data.total;
            this.deviceChannelList = res.data.list;
            // 防止出现表格错位
            this.$nextTick(() => {
              this.$refs.channelListTable.doLayout();
            });
          }
        }).catch(function(error) {
          console.log(error);
        });
      }

    },
    search: function() {
      this.currentPage = 1;
      this.total = 0;
      this.initData();
    },
    updateChannel: function(row) {
      updateChannel(this.deviceId, row).then(function(res) {
        console.log(JSON.stringify(res));
      });
    },
    subStreamChange: function() {
      this.$confirm("确定重置所有通道的码流类型?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateStreamIdentification({
          deviceId: this.deviceId,
          streamIdentification: this.subStream
        }).then((res) => {
          console.log(JSON.stringify(res));
          this.initData();
        }).finally(() => {
          this.subStream = "";
        });
      }).catch(() => {
        this.subStream = "";
      });

    },
    channelSubStreamChange: function(row) {
      updateStreamIdentification({
        deviceId: this.deviceId,
        channelId: row.channelId,
        streamIdentification: row.streamIdentification
      }).then(function(res) {
        console.log(JSON.stringify(res));
      });
    },
    refresh: function() {
      this.initData();
    },
    treeNodeClickEvent: function(device, data, isCatalog) {
      console.log(device);
      if (!data.channelId) {
        this.parentChannelId = device.deviceId;
      } else {
        this.parentChannelId = data.channelId;
      }
      this.initData();
    },
    // 保存
    async handleSave(row) {
      if (row.location) {
        const segements = row.location.split(",");
        if (segements.length !== 2) {
          ElMessage.warning("位置信息格式有误，例：117.234,36.378");
          return;
        } else {
          row.longitude = parseFloat(segements[0]);
          row.latitude = parseFloat(segements[1]);
          if (!(row.longitude && row.latitude)) {
            ElMessage.warning("位置信息格式有误，例：117.234,36.378");
            return;
          }
        }
      } else {
        delete row.longitude;
        delete row.latitude;
      }
      Object.keys(row).forEach(key => {
        const value = row[key];
        if (value === null || value === undefined || (typeof value === "string" && value.trim() === "")) {
          delete row[key];
        }
      });
      await updateChannel(this.deviceId, row);
      this.$modal.msgSuccess("修改成功");
      this.initData();
    },
    // 是否正在编辑
    isEdit() {
      let editing = false;
      this.deviceChannelList.forEach(e => {
        if (e.edit) {
          editing = true;
        }
      });

      return editing;
    },
    // 编辑
    async handleEdit(row) {
      let communityRes = await listCommunity();
      this.communityList = communityRes.rows;
      await this.maChange(row);
      if (this.isEdit()) {
        ElMessage.warning("请保存当前编辑项！");
      } else {
        row.edit = true;
      }
    },
    async maChange(row) {
      let monitorRes = await listMonitorArea({ "communityId": row.communityId });
      this.maList = monitorRes.rows;
      row.maId = undefined;
    }
  }
};
</script>

<style>
.videoList {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.video-item {
  position: relative;
  width: 15rem;
  height: 10rem;
  margin-right: 1rem;
  background-color: #000000;
}

.video-item-img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  height: 100%;
}

.video-item-img:after {
  content: "";
  display: inline-block;
  position: absolute;
  z-index: 2;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 3rem;
  height: 3rem;
  background-image: url("../assets/loading.png");
  background-size: cover;
  background-color: #000000;
}

.video-item-title {
  position: absolute;
  bottom: 0;
  color: #000000;
  background-color: #ffffff;
  line-height: 1.5rem;
  padding: 0.3rem;
  width: 14.4rem;
}
</style>
